package com.queryBuilder.builer;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.Root;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.queryBuilder.util.DocumentUtil;
import com.sun.jersey.spi.template.TemplateContext;

/**
 * 构建自定义查询基础数据结构的工具类
 * 
 * @author pengfei
 */
public class BuilderBasic {

	public static String dataJson;
	private static final String ENTITY_FILENAME = "entityCollection.xml";
	private static final String QUERYTMP_FILENAME = "queryTemplate.xml";

	private static final Log log = LogFactory.getLog(BuilderBasic.class);

	private void builderJson() {
		Document document = DocumentUtil.getDocument(ENTITY_FILENAME);
		List<Element> list = document.selectNodes("/entityList/entity");
		if (list == null || list.isEmpty()) {
			dataJson = null;
			return;
		}
	}

	/**
	 * 获取配置文件中所有的实体类的名称，返回值包含以下属性 entityName :实体类名称 tableName:表名称 group：所属组
	 * 
	 * @return JSONArray
	 * @throws JSONException
	 *             var left = { 01: {id: 01, text: 'Isis'}, 02: {id: 02, text:
	 *             'Sophia'}, 03: {id: 03, text: 'Alice'}, 04: {id: 04, text:
	 *             'Isabella'}, 05: {id: 05, text: 'Manuela'}, 06: {id: 06,
	 *             text: 'Laura'}, 07: {id: 07, text: 'Luiza'}, 08: {id: 08,
	 *             text: 'Valentina'}, 09: {id: 09, text: 'Giovanna'}, 10: {id:
	 *             10, text: 'Maria Eduarda'}, 11: {id: 11, text: 'Helena'}, 12:
	 *             {id: 12, text: 'Beatriz'}, 13: {id: 13, text: 'Maria Luiza'},
	 *             14: {id: 14, text: 'Lara'}, 15: {id: 15, text: 'Julia'}
	 */
	@SuppressWarnings("unchecked")
	public JSONObject getAllEntityName(int count, List<String> entiList) {
		System.out.println("进入");
		Document document = DocumentUtil.getDocument(ENTITY_FILENAME);
		Element root = document.getRootElement();
		List<Element> list = root.elements("entity");
		if (list == null || list.isEmpty()) {
			return null;
		}
		JSONObject sourceJson = new JSONObject();
		try {
			for (Element entity : list) {
				String entityName = entity.attributeValue("className");

				if (entiList != null && entiList.contains(entityName)) {
					continue;
				}

				int temp = ++count;
				JSONObject jsonObject = new JSONObject();
				String tableName = entity.attributeValue("tableName");
				String groupName = entity.attributeValue("group");
				jsonObject.put("entityName", entityName);
				jsonObject.put("tableName", tableName);
				jsonObject.put("group", groupName);
				jsonObject.put("id", temp + "");
				jsonObject.put("text", entityName);
				// jsonArray.add(jsonObject);
				sourceJson.put("" + temp, jsonObject);
			}

		} catch (JSONException e) {
			System.out.println("查询出错，出错信息为：" + e.getMessage());
			e.printStackTrace();
		}
		return sourceJson;
	}

	/**
	 * 获取查询模板中的所有的实体类
	 * 
	 * @param templateName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONArray getAllEntityNameByTemplate(String templateName) {
		JSONArray jsonArray = new JSONArray();
		if (templateName.trim().equals(""))
			return jsonArray;
		Document document = DocumentUtil.getDocument(QUERYTMP_FILENAME);
		Element root = document.getRootElement();
		List<Element> list = root.elements("template");
		if (list == null || list.isEmpty())
			return jsonArray;

		for (Element element : list) {
			List<Element> entityList = element.elements("entity");
			if (entityList != null && !entityList.isEmpty()) {
				for (Element entity : entityList) {
					String entityName = entity.attributeValue("name");
					jsonArray.put(entityName);
				}
			}
		}
		return jsonArray;
	}

	/**
	 * 根据模板名城获取所有的查询类
	 * 
	 * @param templateName
	 * @param count
	 *            技术
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject getEntitiesNameByTemplateName(String templateName) {
		JSONObject jsonObject = new JSONObject();
		if (templateName.trim().equals("")) {
			try {
				jsonObject.put("count", 0);
				jsonObject.put("entities", "[]");

			} catch (Exception e) {
				e.printStackTrace();
			}
			return jsonObject;
		}
		Document document = DocumentUtil.getDocument(QUERYTMP_FILENAME);
		Element root = document.getRootElement();
		List<Element> list = root.elements("template");
		if (list == null || list.isEmpty())
			return jsonObject;
		int index = 1;
		JSONObject endJsonObject = new JSONObject();
		List<String> entitis = new ArrayList<String>();
		try {
			for (Element element : list) {
				String tempName = element.attributeValue("tmpName");
				if (!templateName.equals(tempName)) {
					continue;
				}
				List<Element> entityList = element.elements("entity");
				if (entityList != null && !entityList.isEmpty()) {
					for (Element entity : entityList) {
						JSONObject jsonObject2 = new JSONObject();
						String entityName = entity.attributeValue("name");
						jsonObject2.put("id", index);
						jsonObject2.put("text", entityName);
						entitis.add(entityName);
						jsonObject.put("" + (index++), jsonObject2);
						// jsonArray.put(entityName);
					}
				}
				endJsonObject.put("count", index);
				endJsonObject.put("data", jsonObject);
				endJsonObject.put("entities", entitis);
				break;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return endJsonObject;
	}

	/**
	 * 根据实体类获取实体类的别名
	 * 
	 * @param entityNames
	 *            实体类集合
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, List<String>> getAliasByNames(List<String> entityNames) {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		Document document = DocumentUtil.getDocument(ENTITY_FILENAME);
		if (document == null)
			return null;
		if (entityNames == null || entityNames.isEmpty())
			return null;
		for (String entityName : entityNames) {
			List<String> endList = new ArrayList<String>();
			List<Element> list = document
					.selectNodes("/entityList/entity[@className='" + entityName
							+ "']");
			String alias = list.get(0).attributeValue("alias");
			if (alias == null || alias.equals("null")
					|| alias.trim().equals("")) {
				endList.add(entityName);
			} else {
				String[] temps = alias.split(",");
				endList = Arrays.asList(temps);
			}
			map.put(entityName, endList);
		}
		return map;
	}

	/**
	 * 获取所有的查询模板
	 * 
	 * @return
	 * @throws JSONException
	 */
	@SuppressWarnings("unchecked")
	public JSONArray getAllQueryTemplate() throws JSONException {
		JSONArray jsonArray = new JSONArray();
		Document document = DocumentUtil.getDocument(QUERYTMP_FILENAME);
		Element root = document.getRootElement();
		List<Element> list = root.elements("template");
		// List<Element> list = document.selectNodes("/templates/template");
		if (list == null || list.isEmpty())
			return jsonArray;

		JSONObject jsonObject = null;
		for (Element element : list) {
			jsonObject = new JSONObject();
			String queryTmpId = element.attributeValue("id");
			String queryTmpName = element.attributeValue("tmpName");
			String creatUser = element.attributeValue("createUser");
			String updator = element.attributeValue("updator");
			String lastUpdateDate = element.attributeValue("lastUpdate");

			List<Element> entityList = element.elements("entity");
			int i = 0;
			JSONArray jsonArray2 = new JSONArray();
			if (entityList != null && !entityList.isEmpty()) {
				JSONObject jsonObject2 = null;
				for (Element entity : entityList) {
					jsonObject2 = new JSONObject();
					i++;
					String entityName = entity.attributeValue("name");
					jsonObject2.put("entityName", entityName);
					List<Element> alias = entity.elements("alia");
					JSONArray aliasArray = new JSONArray();
					if (alias != null && !alias.isEmpty()) {
						JSONObject alia = null;
						for (Element aliaElement : alias) {
							alia = new JSONObject();
							String aliaName = aliaElement
									.attributeValue("name");
							alia.put("aliaName", aliaName);
							String properties = aliaElement.getTextTrim();
							alia.put("properties", properties);
							aliasArray.put(alia);
						}
					}
					jsonObject2.put("nodes", aliasArray);
					jsonArray2.put(jsonObject2);
				}
			}
			jsonObject.put("id", queryTmpId);
			jsonObject.put("queryTmpName", queryTmpName);
			jsonObject.put("creatUser", queryTmpName);
			jsonObject.put("updator", updator);
			jsonObject.put("creatUser", creatUser);
			jsonObject.put("lastUpdateDate", lastUpdateDate);
			jsonObject.put("nodes", jsonArray2);
			jsonObject.put("note", element.element("note").getTextTrim());
			// jsonArray.add(jsonObject);
			jsonArray.put(jsonObject);
		}
		return jsonArray;
	}

	/**
	 * 根据模板的Id获取该模板下所有的实体类和实体类对应的别名
	 * 
	 * @param id
	 * @return
	 */
	public List<Map<String, String[]>> getAliasByTmpId(String id) {
		List<Map<String, String[]>> endList = new ArrayList<Map<String, String[]>>();
		Document document = DocumentUtil.getDocument(QUERYTMP_FILENAME);
		List<Element> list = document.selectNodes("/templates/template[@id='"
				+ id + "']");
		if (list == null || list.isEmpty())
			return endList;
		// 模板
		for (Element element : list) {
			// 实体类
			List<Element> entityGroup = element.elements("entity");
			// 模板下面不可能为空
			for (Element entity : entityGroup) {
				Map<String, String[]> map;
				String entityName = entity.attributeValue("name");
				// 别名
				List<Element> aliasElement = entity.elements("alia");
				for (Element aliaNode : aliasElement) {
					map = new HashMap<String, String[]>();
					String[] aliaName = aliaNode.attributeValue("").split(",");
					// String resultPros = aliaNode.getTextTrim();
					map.put(entityName, aliaName);
					endList.add(map);
				}
			}
		}
		return endList;
	}

	/**
	 * 新增查询模板
	 * 
	 * @param tmpName
	 *            模板名称
	 * @param cls
	 *            查询类
	 * @param userName
	 *            用户名称
	 * @return 新增结果
	 */
	public boolean addTemplate(String tmpName, String[] cls, String userName) {
		Map<String, Object> map = DocumentUtil
				.getDocumentAndFile(QUERYTMP_FILENAME);
		Document document = (Document) map.get("document");
		File file = (File) map.get("file");
		Element root = document.getRootElement();
		Element templateNode = root.addElement("template");

		templateNode.addAttribute("tmpName", tmpName);
		templateNode.addAttribute("id", "00001");
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		templateNode.addAttribute("createTime", simpleDateFormat.format(date));
		templateNode.addAttribute("lastUpdate", "");
		templateNode.addAttribute("createUser", userName == null ? "root"
				: userName);
		templateNode.addAttribute("createUser", userName == null ? "root"
				: userName);
		templateNode.addAttribute("updator", "");
		Element entityNode = null;
		for (String entityName : cls) {
			entityNode = templateNode.addElement("entity");
			entityNode.addAttribute("name", entityName);
			Element aliaNode = entityNode.addElement("alia");
			aliaNode.addAttribute("name", entityName + "" + 1);
		}
		templateNode.addElement("note").setText("测试说明");
		return DocumentUtil.writeToXml(document, file);
	}
}
